/**
 * 部门管理
 * 
 * @returns {undefined}
 */
$(function () {

    var departmentContainer = $("#departmentContainer"),
        departments = $("#departments"),
        newDepartment = $("#newDepartment"),
        departmentSelect = $("#departmentSelect"),
        officeHeadSelect = $("#officeHeadSelect"),
        contactPersonSelect = $("#contactPersonSelect"),
        departmentForm = $("#departmentForm"),
        addDepartmentH1 = $("#addDepartmentH1"),
        editDepartmentH1 = $("#editDepartmentH1"),
        departmentTree = $("#departmentTree"),
        // 按钮
        add_department_link = $("#add_department"),
        save_department = $("#save_department"),
        cancel_save = $("#cancel_save"),
        // 缓存
        currentDpart = null,
        dpCache = {},
        rootDp = [],
        employeeCache = null,
        employeeDiv = $("#employeeDiv");

    /**
     * 构建部门结构树
     */
    var buildTree = function (d, parent) {
        var li = $('<li class="dd-item"></li>').data("id", d.id).data("loaded", false);
        li.append($('<div class="dd-handle"></div>').html('<code>' + d.name + '</code>'));
        li.append($('<div class="dd-content"></div>'));
        parent.append(li);
        // 迭代子节点
        if (d.children.length > 0) {
            var ol = $('<ol class="dd-list"></ol>');
            li.append(ol);
            for (var i = 0; i < d.children.length; i++) {
                buildTree(dpCache[d.children[i]], ol);
            }
        }
    };
    /**
     * 初始化结构图
     */
    var initOrganization = function () {
        for (var i = 0; i < rootDp.length; i++) {
            buildTree(dpCache[rootDp[i]], $("#rootOl"));
        }
        //$('#departmentTree').nestable({group: 1});
    };

    /**
     * 初始化部门列表
     */
    var initDepartments = function () {
        chinese.sEmptyTable = "尚未添加部门";
        var table = $('#departmentTable').DataTable({
            "ajax": "department/getAll",
            "sort": false,
            "aoColumnDefs": [
                {
                    "targets": 0, // 折叠按钮
                    "className": 'details-control',
                    "mRender": function (data, type, row) {
                        return '<span class="glyphicons glyphicons-circle_plus text-system cursor-pointer fs14"></span>';
                    }
                }, {
                    "targets": 1, // 部门名称
                    "mRender": function (data, type, row) {
                        return row.name;
                    }
                }, {
                    "targets": 2, // 部门编号
                    "mRender": function (data, type, row) {
                        return row.code || '-';
                    }
                }, {
                    "targets": 3, // 上级部门
                    "mRender": function (data, type, row) {
                        return row.parentName || '-';
                    }
                }, {
                    "targets": 4, // 负责人
                    "mRender": function (data, type, row) {
                        return '<a href="employee/index/' + row.officeHead + '" target="blank">' + row.officeHeadName + '</a>';
                    }
                }, {
                    "targets": 5, // 联系人
                    "mRender": function (data, type, row) {
                        return '<a href="employee/index/' + row.contactPerson + '" target="blank">' + row.contactPersonName + '</a>';
                    }
                }, {
                    "targets": 6, // 员工总数
                    "mRender": function (data, type, row) {
                        return row.employeeCount;
                    }
                }, {
                    "targets": 7, // 操作
                    "mRender": function (data, type, row) {
                        return sys.render("#departmentBtns", row);
                    }
                }],
            "order": [1, 'asc'],
            "oLanguage": chinese,
            "sDom": 't',
            "initComplete": function (settings, json) {
                cacheDepartments(json);
            },
            "rowCallback": function (row, data, index) {
                console.log(data);
                $(row).data("id", data.id).addClass("cursor-pointer text-muted");
            }
        });

        /**
         * 详情展开/关闭
         */
        $('#departmentTable tbody').on('click', 'td.details-control', function (e) {
            e.preventDefault();
            e.stopPropagation();

            var tr = $(this).closest('tr');
            var row = table.row(tr);

            if (row.child.isShown()) {
                // 关闭详情
                $(this).html('<span class="glyphicons glyphicons-circle_plus text-system cursor-pointer fs14"></span>');
                row.child.hide();
                tr.removeClass('shown');
            }
            else {
                // 展开详情
                $(this).html('<span class="glyphicons glyphicons-circle_minus text-info cursor-pointer fs14"></span>');
                var id = row.data().id, dp = dpCache[id], detail = '<p class="text-center mt20 mb20">尚未添加员工</p>';
                dp.status = function () {
                    return this.enabled ? '正常' : '冻结';
                };
                dp.dpid = function () {
                    return dp.id;
                };
                if (dp.members === undefined) {
                    var members = [];
                    dp.members = members;
                    $.get("employee/listByDepartment/" + id, function (res) {
                        if (res.totalSize > 0) {
                            for (var i = 0; i < res.totalSize; i++) {
                                var employee = res.result[i];
                                members.push(employee);
                            }
                            detail = sys.render("#departmentEmployeeTemplate", dp);
                        }
                        row.child(detail).show();
                        tr.addClass('shown');
                    }).fail(function () {
                        alert("网络通信错误");
                    });
                } else {
                    if (dp.members.length > 0) {
                        detail = sys.render("#departmentEmployeeTemplate", dp);
                    }
                    row.child(detail).show();
                    tr.addClass('shown');
                }
            }
        });
    };

    /**
     * 加载部门列表
     */
    var cacheDepartments = function (json) {

        if (json.recordsTotal > 0) {
            // 缓存部门列表
            $.map(json.data, function (d) {
                if (d.id in dpCache) {
                    d.children = dpCache[d.id].children;
                } else {
                    d.children = [];
                }
                dpCache[d.id] = d;

                if (d.parentId === null || d.parentId === '') {
                    rootDp.push(d.id);
                } else {
                    if (d.parentId in dpCache) {
                        dpCache[d.parentId].children.push(d.id);
                    } else {
                        dpCache[d.parentId] = {
                            id: d.parentId,
                            children: [d.id]
                        };
                    }
                }
            });
            /**
             * 渲染部门树
             */
            initOrganization();

//            /**
//             * 渲染部门列表
//             */
//            data.parent = function () {
//                return this.parentName === null ? "无" : this.parentName;
//            };
//            var rendered = sys.render('#departmentTemplate', data);
//            departmentContainer.html(rendered);

            /**
             * 初始化部门下拉列表
             */
            for (var i = 0; i < json.recordsTotal; i++) {
                var d = json.data[i];
                departmentSelect.append($("<option></option>").attr("value", d.id).text(d.name));
            }
        }
    };

    /**
     * 编辑部门时上级部门下拉列表隐藏下属部门，避免逻辑错误
     */
    var hideChildrenOption = function (children) {
        for (var i = 0; i < children.length; i++) {
            $("#departmentSelect option[value=" + children[i] + "]").addClass("hidden");
            hideChildrenOption(dpCache[children[i]].children);
        }
    };

    var openModal = function (target) {
        $.magnificPopup.open({
            removalDelay: 500, //delay removal by X to allow out-animation,
            alignTop: true,
            closeBtnInside: false,
            items: {
                src: target
            },
            callbacks: {
                beforeOpen: function (e) {
                    this.st.mainClass = 'mfp-slideDown';
                }
            },
            midClick: true // allow opening popup on middle mouse click. Always set it to true if you don't provide alternative source.
        });
    };

    /**
     * 初始化按钮事件
     */
    var initEvents = function () {
        // 编辑部门按钮
        departmentContainer.on("click", ".edit-department-link", function (e) {
            e.stopPropagation();
            e.preventDefault();
            var id = $(this).data("id");
            $.get("department/getById/" + id, function (department) {
                if (department) {
                    // 初始化部门信息
                    $("#id").val(department.id);
                    $("#name").val(department.name);
                    $("#code").val(department.code);
                    officeHeadSelect.val(department.officeHead);
                    contactPersonSelect.val(department.contactPerson);
                    $("#description").val(department.description);

                    // 隐藏不可选部门
                    $("#departmentSelect option").removeClass("hidden");
                    departmentSelect.val(department.parentId || "");
                    // 上级部门不可为自己
                    $("#departmentSelect option[value=" + department.id + "]").addClass("hidden");
                    // 上级部门不可为下属部门
                    var myChildren = dpCache[department.id].children;
                    hideChildrenOption(myChildren);

                    // 显示编辑面板
                    addDepartmentH1.hide();
                    editDepartmentH1.show();
                    departments.hide();
                    newDepartment.show();
                } else {
                    alert("部门未找到");
                }
            }).fail("服务器错误");
        });
        // 删除部门按钮
        departmentContainer.on("click", ".delete-department-link", function (e) {
            e.stopPropagation();
            e.preventDefault();
            var id = $(this).data("id");
            if (dpCache[id].children.length > 0) {
                alert("该部门存在下属部门，不可删除。请先移除下属部门后尝试");
                return;
            }
            if (confirm("确认删除部门")) {
                $.get("department/delete/" + id, function (res) {
                    if (res) {
                        alert("部门已删除");
                        location.reload();
                    } else {
                        alert("部门删除失败");
                    }
                }).fail("服务器错误");
            }
        });
        // 添加部门按钮
        add_department_link.on("click", function () {
            $("#id").val("");
            $("#name").val("");
            $("#code").val("");
            departmentSelect.val("");
            $("#officeHead").val("");
            $("#contactPerson").val("");
            $("#description").val("");
            $("#departmentSelect option").removeClass("hidden");
            editDepartmentH1.hide();
            addDepartmentH1.show();
            departments.hide();
            newDepartment.show();
        });
        // 取消部门保存
        cancel_save.on("click", function () {
            newDepartment.hide();
            departments.show();
        });
        // 添加或编辑部门
        save_department.on("click", function () {
            var data = departmentForm.formToJson();
            $.post("department/save", data, function (res) {
                alert(res.message);
                if (res.success) {
                    location.reload();
                }
            }).fail(function () {
                alert("服务器错误");
            });
        });

        /**
         * 添加部门成员
         */
        $('#departmentTable tbody').on('click', '.add-member-link', function (e) {
            e.preventDefault();
            e.stopPropagation();

            var id = $(this).data("id"), dp = dpCache[id], btn = $(this);
            if (employeeCache === null) {
                alert("员工列表为空");
                return;
            }
            $(".member_checkbox").prop("checked", false);
            $(".member_checkbox_div").removeClass("hidden");

            if (dp.employeeCount === employeeCache.length) {
                sys.alert("暂无可添加员工");
                return;
            }
            if (dp.members === undefined) {
                sys.btnSpin(btn);
                var members = [];
                $.get("employee/listByDepartment/" + id, function (res) {
                    if (res.totalSize > 0) {
                        for (var i = 0; i < res.totalSize; i++) {
                            var employee = res.result[i];
                            $("#m-" + employee.id).addClass("hidden");
                            members.push(employee);
                        }
                    }
                    dp.members = members;
                    openModal("#addEmployeePanel");
                    sys.btnStop(btn);

                }).fail(function () {
                    alert("网络通信错误");
                    sys.btnStop(btn);
                });
            } else {
                var mbs = dp.members;
                for (var i = 0; i < mbs.length; i++) {
                    var employee = mbs[i];
                    $("#m-" + employee.id).addClass("hidden");
                }
                openModal("#addEmployeePanel");
            }
            currentDpart = id;
        });

        var getMembers = function () {
            var members = [];
            $.map($(".member_checkbox:checked"), function (box) {
                members.push($(box).val());
            });
            return members.join(",");
        };

        /**
         * 保存部门成员
         */
        $('#saveMemberBtn').on('click', function (e) {
            var btn = $(this), members = getMembers();
            if (currentDpart === null) {
                alert("部门未选择");
                return;
            }
            if (members === '') {
                alert("请选择要添加的员工");
                return;
            }
            sys.btnSpin(btn);
            $.post("employee/saveEmployeeForDepartment", {
                departmentId: currentDpart,
                addIdString: members
            }, function (res) {
                alert(res.message);
                if (res.success) {
                    location.reload();
                }
                sys.btnStop(btn);
            }).fail(function () {
                alert("网络通信错误");
                sys.btnStop(btn);
            });
        });

        /**
         * 删除成员
         */
        $('#departmentTable tbody').on('click', '.delete-member-link', function (e) {
            e.preventDefault();
            e.stopPropagation();

            var id = $(this).data("id");
            if (id === '') {
                alert("员工未找到");
                return;
            }
            if (confirm("确定要删除成员？")) {
                $.post("employee/removeEmployeeFromDepartment", {
                    employeeId: id
                }, function (res) {
                    alert(res.message);
                    if (res.success) {
                        location.reload();
                    }
                }).fail(function () {
                    alert("网络通信错误");
                });
            }
        });

        // 展开/收起员工列表
//        departmentTree.on("click", '.dd-item', function (e) {
//            e.stopPropagation();
//            e.preventDefault();
//            var self = $(this),
//                loaded = self.data("loaded"),
//                id = self.data("id"),
//                content = self.children(".dd-content");
//            if (!loaded) {
//                content.html('<div class="text-center"><i class="fa fa-spinner fa-spin mr5"></i>加载中 ...</div>');
//                $.get("employee/listByDepartment/" + id, function (res) {
//                    if (res.totalSize > 0) {
//                        content.html("");
//                        for (var i = 0; i < res.totalSize; i++) {
//                            var employee = res.result[i];
//                            content.append($('<span class="label label-xs bg-warning light mr5"></span>').text(employee.loginName));
//                            //content.append($('<code class="mr5"></code>').text(employee.loginName));
//                        }
//                    } else {
//                        content.html('<div class="text-center fs12">尚未添加员工</div>');
//                    }
//                    self.data("loaded", true);
//                }).fail(function () {
//                    alert("服务器错误");
//                });
//            }
//            self.toggleClass("toggled");
//        });
    };

    /**
     * 加载员工列表
     */
    var loadEmployees = function () {
        $.get("employee/getData", function (res) {
            var data = res.data;
            if (res.recordsTotal > 0) {
                for (var i = 0; i < data.length; i++) {
                    officeHeadSelect.append($("<option></option>").attr("value", data[i].id).text(data[i].loginName));
                    contactPersonSelect.append($("<option></option>").attr("value", data[i].id).text(data[i].loginName));
                    employeeCache = res.data;
                    var rendered = sys.render("#memberTemplate", {result: res.data});
                    employeeDiv.html(rendered);
                }
            } else {
                officeHeadSelect.append($('<option value="">无</option>'));
                contactPersonSelect.append($('<option value="">无</option>'));
            }
        });
    };

    /**
     * 初始化页面数据
     */
    initDepartments();
    initEvents();
    loadEmployees();
});


